package com.demo.datasource.druid_hibernate_jpa;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;

@Configuration
//@EnableTransactionManagement//已在总开关打开
@EnableJpaRepositories(basePackages = DruidDataSourceConfig.PACKAGE, entityManagerFactoryRef = "druidEntityManagerFactory", transactionManagerRef = "druidTransactionManager")
public class DruidDataSourceConfig {

	static final String PACKAGE = "com.demo.*.repository";
	static final String ENTITY = "com.demo.*.entity";

	@Autowired
	@Qualifier("druidDataSource")
	private DataSource druidDataSource;

	/**
	 * 实体管理对象
	 * 
	 * @param builder
	 *            由spring注入这个对象，首先根据type注入（多个就取声明@Primary的对象），否则根据name注入
	 * @return
	 */
	@Bean("druidEntityManagerFactory")
	@Primary
	public LocalContainerEntityManagerFactoryBean druidEntityManagerFactory(EntityManagerFactoryBuilder builder) {
		return builder.dataSource(druidDataSource).packages(DruidDataSourceConfig.ENTITY).persistenceUnit("repository")
				.build();
	}

	/**
	 * 事务管理对象
	 * 
	 * @return
	 */
	@Bean(name = "druidTransactionManager")
	@Primary
	public PlatformTransactionManager platformTransactionManager(EntityManagerFactory emf) {
		JpaTransactionManager transactionManager = new JpaTransactionManager();
		transactionManager.setEntityManagerFactory(emf);
		return transactionManager;
	}

	@Bean("jdbcTemplate")
	@Primary
	public JdbcTemplate jdbcTemplate() {
		return new JdbcTemplate(druidDataSource);
	}

	@Bean("transactionTemplate")
	@Primary
	public TransactionTemplate transactionTemplate(
			@Qualifier("druidTransactionManager") PlatformTransactionManager druidTransactionManager) {
		return new TransactionTemplate(druidTransactionManager);
	}
}